package org.xtframe.service.impl;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.xtframe.dao.DataBaseDao;
import org.xtframe.dao.DataBaseFactory;
import org.xtframe.entity.ServerData;
import org.xtframe.entity.UserData;
import org.xtframe.service.AjaxDataHandler;
import org.xtframe.service.AjaxDataHandlerException;
import org.xtframe.util.ContextUtil;
import org.xtframe.vo.CheckVO;

@Service
@Scope("prototype")
public class ExecuteUpdateDataHandler extends BasicExecute implements AjaxDataHandler {

	private final Log logger = LogFactory.getLog(getClass());

	public Map<String, Object> execute(String strData) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			UserData userData = ContextUtil.getCurrentUserData();
			ServerData serverData = ContextUtil.getServerData();
			
			JSONObject objJson = JSONObject.fromObject(strData);
			String sqlID = objJson.optString("sqlID", "");
			CheckVO checkVO = check(sqlID, objJson.optString("arrValue", ""), userData, serverData);
			switch(checkVO.getResult()){
				case CheckVO.SQLID_NULL:
					throw new AjaxDataHandlerException("sqlID为空");
				case CheckVO.SQLID_NO_RIGHT:
					map.put(STATUS, false);
					map.put(RIGHT, false);
					throw new AjaxDataHandlerException("不具有该sql("+sqlID+")的执行权限", 1);
				case CheckVO.SQLID_INEXISTENCE:
					throw new AjaxDataHandlerException("该sql("+sqlID+")不存在");
				case CheckVO.CHECK_FAILED:
					throw new AjaxDataHandlerException("sql("+sqlID+")数据格式校验失败");
			}
			
			DataBaseDao dataBaseDao = DataBaseFactory.getDataBaseDaoForSqlId(sqlID);
			int result = dataBaseDao.executeUpdate(checkVO.getSqlData().getSql(), checkVO.getSqlData().getPreparedParameters());
			if(result == -1) {
				map.put(STATUS, false);
				map.put(ROWS, 0);
			} else {
				map.put(STATUS, true);
				map.put(ROWS, result);
			}
		} catch(AjaxDataHandlerException ex){
			logger.warn(ex.toString());
			if(ex.getFlag() == 0){
				map.clear();
				map.put(STATUS, false);
			}
		} catch (Exception e) {
			logger.error(e.toString());
			map.clear();
			map.put(STATUS, false);
		}
		
		return map;
	}

}
